package com.coffee.controller;

import com.coffee.common.BaseContext;
import com.coffee.common.GlobalConstant;
import com.coffee.entity.R;
import com.coffee.entity.ShoppingCart;
import com.coffee.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * 购物车控制器
 */
@RestController
@RequestMapping("/shoppingCart")
@Slf4j
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 新增购物车
     *
     * @param shoppingCartParam
     * @return
     */
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCartParam) {

        //设置用户id，指定当前是哪个用户的购物车数据
        String userId = BaseContext.get();
        shoppingCartParam.setUserId(userId);
        //查询当前咖啡是否在购物车中
        String coffeeId = shoppingCartParam.getCoffeeId();
        //查询数据
        ShoppingCart shoppingCart = shoppingCartService.getCoffeeById(coffeeId, userId);
        //如果存在，就在原来数量基础加一
        if (shoppingCart != null) {
            //购物车 数量+1
            shoppingCart.setNumber(shoppingCart.getNumber() + 1);
            //更新数据
            this.shoppingCartService.updateById(shoppingCart);
        } else {
            //如果不存在就添加到购物车，默认数量就是一
            //shoppingCartParam -> shoppingCart
            shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(shoppingCartParam, shoppingCart);
            shoppingCart.setNumber(1);
            shoppingCart.setId(UUID.randomUUID().toString());
            //在threadlocal中渠道当前用户的id，赋值给要添加的购物车数据，及当前时间
            shoppingCart.setUserId(BaseContext.get());
            shoppingCart.setCreateTime(LocalDateTime.now());
            //新增数据
            this.shoppingCartService.save(shoppingCart);
        }
        return R.success(shoppingCart);
    }

    /**
     * 查询购物车
     *
     * @return
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list() {
        String userId = BaseContext.get();
        List<ShoppingCart> list = shoppingCartService.list(userId);
        return R.success(list);
    }

    /**
     * 删除购物车
     *
     * @return
     */
    @DeleteMapping("/remove")
    public R<String> clean() {
        String userId = BaseContext.get();
        shoppingCartService.remove(userId);
        return R.success(GlobalConstant.FINISH);
    }

    /**
     * 修改购物车（修改咖啡口味和购物车中的咖啡数量）
     *
     * @param shoppingCart
     * @return
     */
    @PutMapping("/update")
    public R<String> update(@RequestBody ShoppingCart shoppingCart) {
        //获取登录用户id
        String userId = BaseContext.get();
        shoppingCart.setUserId(userId);
        this.shoppingCartService.update(shoppingCart);
        return R.success(GlobalConstant.FINISH);
    }

}
